package com.xiaobai.zhuangxiuguanjia.fragments;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.baidu.mapapi.model.LatLng;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.xiaobai.zhuangxiuguanjia.R;
import com.xiaobai.zhuangxiuguanjia.Utils.DingWei;
import com.xiaobai.zhuangxiuguanjia.activities.BaiduMapActivity;
import com.xiaobai.zhuangxiuguanjia.adapters.FindCompanyAdapter;
import com.xiaobai.zhuangxiuguanjia.adapters.GridViewAdapter;
import com.xiaobai.zhuangxiuguanjia.client.FindCompanyAPI;
import com.xiaobai.zhuangxiuguanjia.model.Company;
import com.xiaobai.zhuangxiuguanjia.model.Data;

import org.json.JSONObject;

import java.util.*;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link FindCompanyFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FindCompanyFragment extends Fragment implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private ListView listView;
    private ImageView xianshiweizhi;


    private List<Data> dataList;
    private FindCompanyAdapter findCompanyAdapter;
    private TextView weizhitextview;
    DingWei dingweiInstance;
    private String addrStr;
    private RadioGroup radioGroup;
    private PopupWindow rightPopupWindow;
    private RadioGroup rightRadioGroup;
    private RelativeLayout rightShadow;
    private List<String> diquList;
    private GridViewAdapter gridViewAdapter;
    private GridView leftGridView;
    private RelativeLayout leftShadow;
    private Button qiehuanchengshi;
    private PopupWindow leftPopupWindow;

    private String townId="0";
    private String type="4";
    private String page="1";
    private int page2=1;
    private int diquzhi=1655;
    private RadioButton distance_findCompany;
    private RadioButton district_findCompany;

    String path="http://mobileapi.to8to.com/smallapp.php";
    private DataListLoadTask dataListLoadTask;
    private LatLng latLng;
    private String latitude="40.04275";
    private String longitude="116.376429";
    private PullToRefreshListView pullToRefreshListView;
    private int tag=0;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FindCompanyFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FindCompanyFragment newInstance(String param1, String param2) {
        FindCompanyFragment fragment = new FindCompanyFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public FindCompanyFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        dingweiInstance = DingWei.getInstance(getActivity());
        addrStr = dingweiInstance.getAddrStr();
        latLng = dingweiInstance.getLatLng();
//        Log.d("*****", String.valueOf(latLng.latitude));
//        Log.d("*****", String.valueOf(latLng.longitude));
//

        diquList = new ArrayList<String>();
        diquList.add("全城");
        diquList.add("朝阳区");
        diquList.add("崇文区");
        diquList.add("大兴区");
        diquList.add("东城区");
        diquList.add("房山区");
        diquList.add("丰台区");
        diquList.add("海淀区");
        diquList.add("门头沟区");
        diquList.add("平谷区");
        diquList.add("石景山区");
        diquList.add("顺义区");
        diquList.add("通州区");
        diquList.add("西城区");
        diquList.add("宣武区");
        diquList.add("昌平区");
        diquList.add("怀柔区");
        diquList.add("密云县");
        diquList.add("延庆县");

        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        dataList=new LinkedList<Data>();
        findCompanyAdapter=new FindCompanyAdapter(getActivity(),dataList);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_find_company, container, false);
        radioGroup = (RadioGroup) view.findViewById(R.id.twospinner);
        radioGroup.setOnCheckedChangeListener(this);
        distance_findCompany = (RadioButton) view.findViewById(R.id.distance_findCompany);
        distance_findCompany.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (rightPopupWindow.isShowing()) {
                    rightPopupWindow.dismiss();
                } else rightPopupWindow.showAsDropDown(radioGroup);
            }
        });
        district_findCompany = (RadioButton) view.findViewById(R.id.district_findCompany);
        district_findCompany.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (leftPopupWindow.isShowing()) {
                    leftPopupWindow.dismiss();
                } else leftPopupWindow.showAsDropDown(radioGroup);
            }
        });


        pullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.listView_findCompany);
        xianshiweizhi = (ImageView) view.findViewById(R.id.xianshiweizhi);
        xianshiweizhi.setOnClickListener(this);
        LinearLayout headerLinearLayout = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.findcompanyheadview, null);

//        textView.setText(addrStr);
        weizhitextview = (TextView) headerLinearLayout.findViewById(R.id.weizhitextview);
        ImageView weizhishuaxin= (ImageView) headerLinearLayout.findViewById(R.id.weizhishuaxin);
        weizhishuaxin.setOnClickListener(this);
        weizhitextview.setText("当前位置 : " + addrStr);
        listView= pullToRefreshListView.getRefreshableView();

        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {



            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                Toast.makeText(getActivity(), "pulldown", Toast.LENGTH_SHORT).show();
                page2=1;
                dataListLoadTask = new DataListLoadTask();
                dataListLoadTask.execute(path, townId, type, longitude, latitude,page);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                Toast.makeText(getActivity(), "pullup", Toast.LENGTH_SHORT).show();
                dataListLoadTask = new DataListLoadTask();
                page2++;
                dataListLoadTask.execute(path, townId, type, longitude, latitude,String.valueOf(page2));
                tag=1;
            }
        });
        listView.addHeaderView(headerLinearLayout);
        listView.setAdapter(findCompanyAdapter);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        dataListLoadTask = new DataListLoadTask();

//        longitude = String.valueOf(latLng.longitude);
//        latitude = String.valueOf(latLng.latitude);
//        String path="http://mobileapi.to8to.com/smallapp.php?uid=&model=company&cityName=%E5%8C%97%E4%BA%AC&townId=0&appid=1&appversion=2.5.1&perPage=30&type=4&appostype=1&to8to_token=&version=2.5&page=1&action=list&longitude=116.376301&latitude=40.042872&systemversion=19&channel=sanliuling&paging=true&";
        dataListLoadTask.execute(path, townId, type,longitude,latitude,page);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.xianshiweizhi:
                Intent intent = new Intent(getActivity(), BaiduMapActivity.class);
                startActivity(intent);
                break;
            case R.id.weizhishuaxin:
                String s = dingweiInstance.getAddrStr();
                if(!s.equals(addrStr)){
                    weizhitextview.setText("当前位置 : "+s);
                }
                break;

        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId){
            case R.id.district_findCompany:
                View leftView =LayoutInflater.from(getActivity()).inflate(R.layout.left_popupmenu, null);
                qiehuanchengshi = (Button) leftView.findViewById(R.id.leftview_qiehuan);
                qiehuanchengshi.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getActivity(), "切换城市", Toast.LENGTH_SHORT).show();
                    }
                });
                leftGridView = (GridView) leftView.findViewById(R.id.leftview_gridview);
                gridViewAdapter = new GridViewAdapter(getActivity(), diquList);
                leftGridView.setAdapter(gridViewAdapter);
                leftPopupWindow = new PopupWindow(leftView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
                leftPopupWindow.setTouchable(true);
                leftPopupWindow.setFocusable(true);
                leftPopupWindow.setOutsideTouchable(true);
                leftPopupWindow.setBackgroundDrawable(new BitmapDrawable());

                leftGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        leftPopupWindow.dismiss();
                        Toast.makeText(getActivity(), "点击了" + position, Toast.LENGTH_SHORT).show();
                        page2=1;
                        district_findCompany.setText(diquList.get(position));
                        if(position==17){
                            townId="1673";
                        }else if(position==18){
                            townId="1674";
                        }else{
                            townId=String.valueOf(diquzhi+position);
                        }
                        dataListLoadTask = new DataListLoadTask();
                        dataListLoadTask.execute(path, townId, type,longitude,latitude,page);

                    }
                });

                leftShadow = (RelativeLayout) leftView.findViewById(R.id.left_menu_shadow);
                leftShadow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getActivity(), "阴影点击消失", Toast.LENGTH_SHORT).show();
                        page2=1;
                        leftPopupWindow.dismiss();
                    }
                });
                leftPopupWindow.showAsDropDown(group);

                break;
            case R.id.distance_findCompany:
                View rightView =LayoutInflater.from(getActivity()).inflate(R.layout.right_popupmenu, null);
                rightPopupWindow = new PopupWindow(rightView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
                rightPopupWindow.setTouchable(true);
                rightPopupWindow.setOutsideTouchable(true);
                rightPopupWindow.setBackgroundDrawable(new BitmapDrawable());
                rightRadioGroup = (RadioGroup) rightView.findViewById(R.id.right_radiogroup);

                rightShadow = (RelativeLayout) rightView.findViewById(R.id.right_menu_shadow);
                rightShadow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getActivity(), "阴影点击消失", Toast.LENGTH_SHORT).show();
                        page2=1;
                        rightPopupWindow.dismiss();
                    }
                });
                rightRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        page2=1;
                        switch (checkedId) {
                            case R.id.right_koubeizuihao:
                                Toast.makeText(getActivity(),"口碑最好",Toast.LENGTH_SHORT).show();
                                distance_findCompany.setText("口碑最好");
                                type="4";
                                 dataListLoadTask = new DataListLoadTask();
                                dataListLoadTask.execute(path, townId, type,longitude,latitude,page);

                                break;
                            case R.id.right_liwozuijin:
                                Toast.makeText(getActivity(),"离我最近",Toast.LENGTH_SHORT).show();
                                distance_findCompany.setText("离我最近");
                                type="1";
                                dataListLoadTask = new DataListLoadTask();
                                dataListLoadTask.execute(path, townId, type,longitude,latitude,page);
                                break;
                        }
                        rightPopupWindow.dismiss();

                    }
                });
                rightPopupWindow.showAsDropDown(group);
                break;

        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

    private class DataListLoadTask extends AsyncTask<String,Void,JSONObject>{

        private HashMap<String, String> params2;

        @Override
        protected JSONObject doInBackground(String... params) {
            JSONObject ret=null;
            if(params!=null&&params.length>0){
                params2 = new HashMap<String,String>();

                params2.put("uid","");
                params2.put("model","company");
                params2.put("cityName","北京");
                params2.put("townId",params[1]);
                params2.put("appid","1");
                params2.put("appversion","2.5.1");
                params2.put("perPage","30");
                params2.put("type",params[2]);
                params2.put("appostype","1");
                params2.put("to8to_token","");
                params2.put("version","2.5");
                params2.put("page",params[5]);
                params2.put("action","list");
                params2.put("longitude",params[3]);
                params2.put("latitude",params[4]);
                params2.put("systemversion","19");
                params2.put("channel","sanliuling");
                params2.put("paging","true");

                ret= FindCompanyAPI.getJSONObject(params[0], params2);
//                ret= FindCompanyAPI.getJSONObject(params[0]);
            }
            return ret;
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {

            if (jsonObject != null) {
                Company company = new Company();
                company.parseJSON(jsonObject);
                List<Data> dataList1 = company.getDataList();
                Log.d("----->", dataList1.toString());
                if(tag==0){

                    dataList.clear();
                }
                dataList.addAll(dataList1);
                tag=0;
                findCompanyAdapter.notifyDataSetChanged();
                if(pullToRefreshListView.isRefreshing()){
                    pullToRefreshListView.onRefreshComplete();
                }
            }

        }
    }
}
